<template>
    <el-dialog v-model="dialogVisible" title="新增消费记录" width="360px" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="pt10 pr15">
            <el-form-item label="订单号" prop="sn">
                <el-input
                    id="sn"
                    v-model="ruleForm.sn"
                    show-word-limit
                    maxlength="32"
                    placeholder="请输入订单号"
                    clearable
                    @input="inputSn"
                />
            </el-form-item>
            <el-form-item label="消费商户" prop="shop_id">
                <el-select-v2
                    id="shop_id"
                    v-model="ruleForm.shop_id"
                    :props="{ value: 'id', label: 'name' }"
                    :options="shopOptions"
                    placeholder="请选择消费商户"
                    filterable
                />
            </el-form-item>
            <el-form-item label="消费金额" prop="paid_amount">
                <GInputNumber
                    id="price"
                    v-model="ruleForm.paid_amount"
                    type="decimal"
                    decimal="2"
                    placeholder="请输入消费金额"
                    clearable
                    @input="inputReprice"
                />
            </el-form-item>
            <el-form-item label="确认消费金额" prop="reprice">
                <GInputNumber
                    id="reprice"
                    v-model="ruleForm.reprice"
                    clearable
                    type="decimal"
                    decimal="2"
                    placeholder="请输入确认消费金额"
                />
            </el-form-item>
            <el-form-item label="支付方式" prop="pay_way">
                <el-select id="pay_way" v-model="ruleForm.pay_way" placeholder="请选择支付方式" @change="changePayWay">
                    <el-option
                        v-for="row in payWayFilters"
                        :key="row.value"
                        :value="row.value"
                        :label="row.label"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-if="showPaidSource" :label="`${ruleForm.pay_way}交易号`" prop="transaction_source">
                <el-input
                    id="transaction_source"
                    v-model="ruleForm.transaction_source"
                    placeholder="请输入交易号"
                    clearable
                />
            </el-form-item>
            <el-form-item label="消费时间" prop="paid_at">
                <el-date-picker
                    id="ordered_at"
                    v-model="ruleForm.paid_at"
                    :editable="false"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="选择消费时间"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="cancelDialog">取消</el-button>
            <el-button type="primary" :loading="subLoading" :disabled="subLoading" @click="submitForm(ruleFormRef)">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { reactive, ref, watch, nextTick, computed } from "vue";
    import { getShowPaidSource } from "@/filters/data";
    import { FPayWayFilters } from "@/filters";
    import { TypeFilters } from "@/interface/filters";
    import { getApiMajorListFilter } from "@/assets/api/handler";
    import { _mallStore } from "@/store/config";

    // 多张小票
    const isMoreImage = computed(() => {
        const ticket: ObjValueAny = _mallStore.mallZeusConfig.ticket || {};
        return !(ticket.support_ocr == 1 && ticket.image_type == 1);
    })

    const payWayFilters = reactive<TypeFilters.filter[]>(FPayWayFilters);

    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false,
        },
        memberId: {
            type: Number,
            default: 0,
        },
    })

    const ruleForm = reactive<ObjValueAny>({
        member_id: props.memberId,
        sn: '',
        shop_id: '',
        paid_amount: '',
        reprice: '',
        pay_way: '',
        transaction_source: '',
        paid_at: '',
    });

    let dialogVisible = ref<boolean>(false);// 显示弹窗
    let subStatus: boolean = false;
    let subLoading = ref<boolean>(false);
    const ruleFormRef = ref();

    const showPaidSourceValue = ref<string[]>(getShowPaidSource());// 显示交易号
    const showPaidSource = computed(() => {
        return showPaidSourceValue.value.includes(ruleForm.pay_way)
    })

    const inputSn = (str: string = '') => {
        ruleForm.sn = str.replace(/[^0-9a-zA-Z\x21-\x2f\x3a-\x40\x5b-\x60\x7B-\x7F\s]/g, '');
    }
    const changePayWay = () => {
        if (showPaidSource.value) {
            nextTick(() => {
                ruleFormRef.value.validateField('transaction_source', () => {
                })
            })
        } else {
            ruleForm.transaction_source = '';
        }
    }
    const inputReprice = () => {
        ruleFormRef.value.validateField('reprice', () => {
        })
    }


    const formStringEmptyRule = (message: string) => {
        return (rule: ObjValueAny, value: string, callback: Function) => {
            if (subStatus && !value) {
                return callback(new Error(message));
            }
            callback()
        }
    }
    const formSnRule = (rule: ObjValueAny, value: string, callback: Function) => {
        if (isMoreImage.value && subStatus && !value) {
            return callback(new Error('请输入订单号'))
        }
        callback()
    }
    const validatorReprice = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus) {
            if (!value) {
                return callback(new Error('请输入确认消费金额'))
            }
            if (+ruleForm.paid_amount !== +value) {
                return callback(new Error('消费金额不一致，请确认消费金额'))
            }
        }
        callback()
    }
    const validatorSource = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && showPaidSource.value && !value) {
            return callback(new Error('请输入交易号'))
        }
        callback()
    }
    const rules = reactive<ObjValueAny>({
        sn: [{ required: true, validator: formSnRule, trigger: 'change' }],
        shop_id: [{ required: true, validator: formStringEmptyRule('请选择消费的商户'), trigger: 'change' }],
        paid_amount: [{ required: true, validator: formStringEmptyRule('请输入消费金额'), trigger: 'change' }],
        reprice: [{ required: true, validator: validatorReprice, trigger: 'change' }],
        pay_way: [{ required: true, validator: formStringEmptyRule('请选择支付方式'), trigger: 'change' }],
        transaction_source: [{ required: true, validator: validatorSource, trigger: 'change' }],
        paid_at: [{ required: true, validator: formStringEmptyRule('请选择消费时间'), trigger: 'change' }],
    })
    const submitForm = (formEl: any) => {
        subStatus = true;
        if (!formEl) return;
        formEl.validate((valid: boolean, fields: ObjValueAny) => {
            if (valid) {
                console.log('submit!');
                onSave();
            } else {
                console.log('error submit!', fields);
            }
        });
    }
    // 店铺筛选
    const shopOptions = ref<ObjValueAny[]>([]);
    const getShopList = async () => {
        shopOptions.value = await getApiMajorListFilter(false);
    }
    // 监听 弹窗显示隐藏
    watch(() => props.modelValue, (newVal: boolean) => {
        if (newVal) {
            getShopList();
        }
        dialogVisible.value = newVal;
        subLoading.value = false;
        subStatus = false;
    })
    const emit = defineEmits(['update:modelValue', 'add']);
    // 关闭弹窗
    const closeDialog = () => {
        cancelDialog();
        emit('update:modelValue', dialogVisible.value)
    }
    // 关闭弹窗
    const cancelDialog = () => {
        resetRuleForm(ruleFormRef.value);
        dialogVisible.value = false;
    }
    const resetRuleForm = (formEl: any) => {
        if (!formEl) return;
        formEl.resetFields();
    }
    const onSave = () => {
        subLoading.value = true;
        const data: ObjValueAny = getRuleFormHandler();
        console.info(data);
        // postRestfulMallOrder(data).then(() => {})
    }
    const getRuleFormHandler = () => {
        const data: ObjValueAny = { ...ruleForm };
        delete data.reprice;
        return data;
    }
</script>